#!/bin/bash

# Deployment script for Wan 2.2 Video Generation API
# This script should be run on the server

set -e  # Exit on error

# Configuration
DOCKER_COMPOSE_FILE="docker-compose.yml"
ENV_FILE=".env"
BACKUP_DIR="./backup_$(date +%Y%m%d_%H%M%S)"

# Colors for output
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

echo -e "${GREEN}🚀 Starting Wan 2.2 Video Generation API deployment...${NC}"

# Check if .env exists
if [ ! -f "$ENV_FILE" ]; then
    echo -e "${YELLOW}⚠️  Warning: $ENV_FILE not found. Please create it from .env.example${NC}"
    exit 1
fi

# Check if docker is installed and running
if ! command -v docker &> /dev/null; then
    echo -e "${YELLOW}❌ Docker is not installed. Please install Docker first.${NC}"
    exit 1
fi

if ! docker info &> /dev/null; then
    echo -e "${YELLOW}❌ Docker daemon is not running. Please start Docker.${NC}"
    exit 1
fi

# Check if docker-compose is installed
if ! command -v docker-compose &> /dev/null; then
    echo -e "${YELLOW}❌ docker-compose is not installed. Please install docker-compose.${NC}
    echo "You can install it with: sudo curl -L \"https://github.com/docker/compose/releases/latest/download/docker-compose-$(uname -s)-$(uname -m)\" -o /usr/local/bin/docker-compose && sudo chmod +x /usr/local/bin/docker-compose"
    exit 1
fi

# Create backup of existing deployment
if [ -d "data" ] || [ -d "logs" ]; then
    echo -e "${GREEN}📦 Creating backup of existing data...${NC}"
    mkdir -p "$BACKUP_DIR"
    [ -d "data" ] && cp -r data "$BACKUP_DIR/"
    [ -d "logs" ] && cp -r logs "$BACKUP_DIR/"
    echo -e "✅ Backup created at $BACKUP_DIR"
fi

# Stop and remove existing containers
echo -e "\n${GREEN}🛑 Stopping and removing existing containers...${NC}"
docker-compose down --remove-orphans

# Pull latest changes
echo -e "\n${GREEN}🔄 Pulling latest changes...${NC}
git pull origin main  # or your branch name

# Rebuild and start containers
echo -e "\n${GREEN}🚀 Building and starting containers...${NC}
docker-compose up -d --build

# Check if the API is healthy
echo -e "\n${GREEN}🩺 Checking API health...${NC}
for i in {1..10}; do
    if curl -s -f http://localhost:8000/health > /dev/null; then
        echo -e "✅ API is up and running!"
        echo -e "\n${GREEN}🎉 Deployment completed successfully!${NC}"
        echo -e "\nAccess the API at: http://your-server-ip:8000"
        echo -e "API documentation: http://your-server-ip:8000/docs"
        exit 0
    fi
    echo "Waiting for API to start... (attempt $i/10)"
    sleep 5
done

echo -e "${YELLOW}⚠️  Warning: API did not start successfully. Check the logs with 'docker-compose logs -f'${NC}"
exit 1
